package ru.nnstu.client.gui;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.apache.log4j.Logger;

import ru.nnstu.client.ClientLauncher;
import ru.nnstu.server.PlayerImpl;

import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;

public class ClientViewer extends JPanel implements ActionListener {
	private static final Logger LOG = Logger.getLogger(ClientViewer.class);
	private static DefaultTableModel dm;
	private JTable table = new JTable();
	private JButton refreshButton;
	private JButton closeButton;
	private static HashSet<String> dataTable = new HashSet<String>();

	public ClientViewer() {
		setLayout(new GridBagLayout());

		refreshButton = new JButton("Refresh List");
		refreshButton.setSize(50, 80);
		refreshButton.setEnabled(true);
		// refreshButton.setBounds(0, 0, 122, 122);
		refreshButton.setVisible(true);
		refreshButton.setActionCommand("refresh");
		refreshButton.addActionListener(this);
		// refreshButton.setVerticalAlignment(SwingConstants.BOTTOM);
		// refreshButton.setHorizontalAlignment(SwingConstants.RIGHT);

		closeButton = new JButton("Close");
		closeButton.setSize(50, 80);
		closeButton.setEnabled(true);
		closeButton.setVisible(true);
		closeButton.setActionCommand("exit");
		closeButton.addActionListener(this);
		// closeButton.setVerticalAlignment(SwingConstants.BOTTOM);
		// closeButton.setHorizontalAlignment(SwingConstants.RIGHT);

		String[] columnNames = { "Name", "Sex", "Date creating" };
		Object[][] data = new Object[0][columnNames.length];
		dm = new DefaultTableModel(data, columnNames);
		// table = new JTable(data, columnNames);
		table.setModel(dm);
		table.setPreferredScrollableViewportSize(new Dimension(640, 480));
		// table.setFillsViewportHeight(true);
		// Create the scroll pane and add the table to it.
		JScrollPane scrollPane = new JScrollPane(table);

		// Add the scroll pane to this panel.
		add(scrollPane);
		add(refreshButton);
		add(closeButton);
	}

	public void actionPerformed(ActionEvent e) {
		if ("refresh".equals(e.getActionCommand())) {
			// b2.setEnabled(false);
			LOG.info("Pressed RefreshButton!");
			loadAllData();

		} else if ("exit".equals(e.getActionCommand())) {
			System.exit(0);
		}
	}

	@SuppressWarnings("unused")
	private void printDebugData(JTable table) {
		int numRows = table.getRowCount();
		int numCols = table.getColumnCount();
		javax.swing.table.TableModel model = table.getModel();

		System.out.println("Value of data: ");
		for (int i = 0; i < numRows; i++) {
			System.out.print("    row " + i + ":");
			for (int j = 0; j < numCols; j++) {
				System.out.print("  " + model.getValueAt(i, j));
			}
			System.out.println();
		}
		System.out.println("--------------------------");
	}

	/**
	 * Create the GUI and show it. For thread safety, this method should be
	 * invoked from the event-dispatching thread.
	 */
	private static ClientViewer newContentPane;

	private static void createAndShowGUI() {
		// Create and set up the window.
		JFrame frame = new JFrame("Player Monitor");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Create and set up the content pane.
		newContentPane = new ClientViewer();
		newContentPane.setOpaque(true); // content panes must be opaque
		frame.setContentPane(newContentPane);

		// Display the window.
		frame.pack();
		frame.setVisible(true);
		// updateAdd();
		loadAllData();
	}

	public static void main(String[] args) {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		// javax.swing.SwingUtilities.invokeLater(new Runnable() {
		// public void run() {
		// createAndShowGUI();
		// }
		// });
		createAndShowGUI();
	}

	public static void updateAdd(Object obj) {
		PlayerImpl player = null;
		try {
			player = (PlayerImpl) obj;
		} catch (Exception e) {
			LOG.error("Unable to cast obj to PlayerImpl");
		}
		String[] dat = new String[3];
		dat[0] = player.getName();
		dat[1] = player.getSex();
		dat[2] = player.getDateCreating().toString();
		String commit = "";
		for (String i : dat) {
			commit += i;
		}
		if (!dataTable.contains(commit)) {
			dataTable.add(commit);
			dm.addRow(dat);
			dm.fireTableDataChanged();
		}
	}

	private static void loadAllData() {
		ArrayList<PlayerImpl> listPlayer = ClientLauncher.getPlayerservice()
				.getAllPlayerImpls();
		if (listPlayer.isEmpty()) {
			LOG.info("Nothing to load");
		} else {

			for (PlayerImpl i : listPlayer) {

				updateAdd(i);
			}
		}
	}
}